/**
 * 
 */
package br.financeiro.masks;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * @author evaldosavio, nayraoliviera
 * 
 */
public class EditMask implements TextWatcher {
	private final EditText edt;
	private boolean isUpdating = false;
	private String mask;

	/**
	 * @param edt
	 * @date_modify Feb 23, 2013
	 * @author evaldosavio,nayraoliviera
	 */
	public EditMask( EditText edt, String mask ) {
		this.edt = edt;
		this.mask = mask;
		this.edt.setFilters( new InputFilter[] { new InputFilter.LengthFilter( mask.length() ) } );
	}

	@Override
	public void afterTextChanged( Editable arg0 ) {

	}

	@Override
	public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3 ) {}

	/**
	 * @author evaldosavio,nayraoliviera
	 */
	@Override
	public void onTextChanged( CharSequence s, int start, int before, int after ) {
		if ( isUpdating ) {
			return;
		}
		isUpdating = true;

		String text = getText();
		text = text.replaceAll( "([\\W_])", "" );

		// Se after > before significa que o usuario esta digitando, caso
		// contrario esta apagando
		if ( after > before ) {
			edt.setText( mountMask( text ) );

			if ( start == getText().length() ) {
				edt.setSelection( start );
				return;
			}

			char token = mask.charAt( start );
			while ( token != '_' && token != '#' ) {
				token = mask.charAt( ++start );
			}
			edt.setSelection( start + 1 <= getText().length() ? start + 1 : start );

		} else if ( after < before ) {

			edt.setText( mountMask( text ) );

			if ( start > getText().length() ) {
				start--;
			}
			edt.setSelection( start );
		}
		isUpdating = false;
	}

	/**
	 * formatar o texto de acordo com a máscara
	 * 
	 * @data_modificacao Feb 25, 2013
	 * @author evaldosavio,nayraoliviera
	 * @param text
	 * @param str
	 * @return
	 */

	private String mountMask( String text ) {
		String str = "";
		for ( int i = 0, j = 0; i < text.length(); i++, j++ ) {
			if ( "#_".contains( mask.charAt( j ) + "" ) ) {
				str += text.charAt( i );
			} else {
				str += mask.charAt( j );
				i--;
			}
		}
		return str;
	}

	private String getText() {
		return edt.getText().toString();
	}
}
